/*
files.js - HTML5 File Drag & Drop demonstration
Featured on SitePoint.com
Original by Craig Buckler (@craigbuckler) of OptimalWorks.net
Adapted by Pierre Quentel pierre.quentel@gmail.com
*/

var underFly = null;
var ctarget = null;

// getElementById
function $id(id) {
    return document.getElementById(id);
}

function getPosition(e){
    var left = 0;
    var top  = 0;
    var width = e.offsetWidth;
    var height = e.offsetHeight;

    while (e.offsetParent){
        left += e.offsetLeft;
        top  += e.offsetTop;
        e     = e.offsetParent;
    }

    left += e.offsetLeft;
    top  += e.offsetTop;

    return {x:left, y:top, width:width, height:height};
}

// output information
function Output(msg) {
    var m = $id("messages");
    m.innerHTML = msg + m.innerHTML;
}

// start dragging a file inside file browser
function pick(e){
    e.target.style.borderWidth="1px";
    e.target.style.borderStyle="solid";
    e.target.style.borderColor="#FF8";
    e.dataTransfer.effectAllowed='move';
    e.dataTransfer.setData('Text',e.target.innerHTML)
    Output(e.target.innerHTML)
}

// file drag hover
function filesHover(e) {
    if(!e.dataTransfer){
        if(e.type=="dragover"){
            $id("files").className = "hover"
        } else {
            $id("files").className = ""
        }
    }
    //e.stopPropagation();
    e.preventDefault();
}

function errorHandler(evt) {
    switch(evt.target.error.code) {
      case evt.target.error.NOT_FOUND_ERR:
        alert('File Not Found!');
        break;
      case evt.target.error.NOT_READABLE_ERR:
        alert('File is not readable');
        break;
      case evt.target.error.ABORT_ERR:
        break; // noop
      default:
        alert('An error occurred reading this file.');
    };
}

function updateUploadProgress(evt){
if (evt.lengthComputable) {  
    var percentLoaded = parseInt(100*(evt.loaded / evt.total));
    progress = $id('pcbar')
    progress.style.width = percentLoaded + '%';
    progress.innerHTML = percentLoaded + '%';
  }
}

function load_all(file,data){
    var boundary = '------multipartformboundary' + (new Date).getTime();
    /* Build RFC2388 string. */

    var content = '--'+boundary+'\r\n';

    /* send folder. */
    content += 'Content-Disposition: form-data; name="folder"\r\n';
    content += 'Content-Type: text/plain;\r\n\r\n'
    content += folder; // name folder is in Javascript namespace
    content += '\r\n';

    /* Write boundary. */
    content += '--'+boundary;
    content += '\r\n';


    /* Generate headers. */
    content += 'Content-Disposition: form-data; name="src"';
    if (file.name) {
      content += '; filename="' + file.name + '"\r\n';
    }

    content += 'Content-Type: '+file.type+"\r\n\r\n";

    /* Write data */
    content += data
    content += '\r\n';

    /* Mark end of the request. */
    content += '--'+boundary+'--\r\n';

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                resp = xhr.responseText
                if(resp != "ok"){
                    msg = '<b style="color:red;">Your changes could not been saved</b>'
                    msg += ' - Error status '+xhr.status
                    Output(msg);
                    Output('<pre>'+resp+'</pre>')
                } else {
                    Output('finished')
                    progress = $id('pcbar')
                    progress.style.width = '100%';
                    progress.innerHTML = '100%';
                    // refresh page
                    location.href = "index?folder="+folder
                }
            } else {
                msg = '<b style="color:red;">Your changes could not been saved</b>'
                msg += ' - Error status '+xhr.status
                Output(msg)
            }
        }
    }
    xhr.upload.addEventListener("progress",updateUploadProgress,false)
    xhr.open("POST", "upload_dd", true);
    xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' 
        + boundary);
    xhr.send(content);

}

function upload(event) {
    
    var data = event.dataTransfer;
    Output(data.files.length+' files ')
    
    if(data.files.length==0){
        alert(data.getData('Text')+' '+event.target.innerHTML)
        event.stopPropagation();
        event.preventDefault()
        $id('files').className=""
        return
    }

    /* dropped file. */
    var file = data.files[0];
    
    status = "ok"
    /* first ask server if file of same name exists in folder */
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                resp = xhr.responseText
                if(resp=="True"){
                    // file of same name exists
                    res = confirm("File of same name exists - Override ?")
                    if(!res){status="no_override"}
                } else if(resp!="False") {
                    // something went wrong
                    msg = '<b style="color:red;">Your changes could not been saved</b>'
                    msg += ' - Error status '+xhr.status
                    Output(msg);
                    Output('<pre>'+resp+'</pre>')
                    return
                }
            } else {
                msg = '<b style="color:red;">Your changes could not been saved</b>'
                msg += ' - Error status '+xhr.status
                Output(msg)
                return
            }
        }
    }
    // set mode = false : if file exists and user doesn't want to override,
    // the next request must not be sent
    xhr.open("GET", "file_exists?folder="+folder+"&name="+file.name, false);
    xhr.setRequestHeader('Content-type','text/plain')
    xhr.send();
    
    if(status=="no_override"){
        event.stopPropagation();
        event.preventDefault();
        $id("files").className = ""
        return
    }
    
    /* show progress bar */
    $('upload_info').style.visibility="visible";

    /* Append binary data. */
    reader = new FileReader()
    
    reader.onerror = errorHandler;
    reader.onabort = function(e) {
      alert('File read cancelled');
    };
    reader.onloadstart = function(e) {
      $id('progress_bar').className = 'loading';
      Output('Loading '+file.name+'...')
    };
    reader.onload = function (e){
        load_all(file,e.target.result)
    }
    reader.readAsDataURL(file);
    
    /* Prevent FireFox opening the dragged file. */
    event.stopPropagation();
    event.preventDefault();
    $id("files").className = ""
}

// initialize
function Init() {

    files = $id("files")

    // is XHR2 available?
    var xhr = new XMLHttpRequest();
    if (xhr.upload) {

        // file drop
        files.addEventListener("dragover", filesHover, false);
        files.addEventListener("drop", upload, false);
        files.style.display = "block";

    }
    
}

// call initialization file
if (window.File && window.FileList && window.FileReader) {
    Init();
}


